package com.starking.wxx.http;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * @描述:
 * @文件名: Main.java
 * @创建人: wangxinxin
 * @创建时间: 2018/11/8
 * @修改人: wangxinxin
 * @修改备注: <br/>
 * <p>
 */
public class Main {
    public static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        doPost();
    }

    /**
     * http发送post请求
     */
    private static void doPost() {
        String url = "http://k2interface.web.58dns.com:8080/elephant/invoice/invoiceFileUpload";

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {

            HttpPost httpPost = new HttpPost(url);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

            //普通参数
            entityBuilder.addTextBody("zs1", "zhangsan1");
            entityBuilder.addTextBody("zs2", "zhangsan2");
            entityBuilder.addTextBody("zs3", "zhangsan3");
            //文件参数
            File file = new File("C://1.png");
            FileBody imgBody = new FileBody(file);
            entityBuilder.addPart("imgFile", imgBody);

            httpPost.setEntity(entityBuilder.build());
            CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
            String resultString = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            LOGGER.info("resultString = " + resultString);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
